package com.ct.gd.passport.service;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.Header;
import org.apache.http.HttpResponse;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.Log;

import com.ct.gd.passport.common.CTApp;
import com.ct.gd.passport.common.connect.CtServer;
import com.ct.gd.passport.common.constants.Config;
import com.ct.gd.passport.common.constants.Protocol;
import com.ct.gd.passport.common.constants.UmengVar;
import com.ct.gd.passport.common.mock.ConnectRequest;
import com.ct.gd.passport.common.mock.Cookie;
import com.ct.gd.passport.common.mock.HttpConnectClient;
import com.ct.gd.passport.common.mock.RequestAdapter;
import com.ct.gd.passport.domain.PassportGoApply;
import com.ct.gd.passport.domain.PassportInfo;
import com.ct.gd.passport.util.TelephonyState;
import com.fuckhtc.gson.Gson;
import com.umeng.analytics.MobclickAgent;
import com.up91.common.android.connect.Params;
import com.up91.common.android.helper.L;

public class PassportService {

	public static Cookie cookie = null;

	public static String scriptSessionId = "" + System.currentTimeMillis();

	/***
	 * 通过通行证号获取一个通行证信息对象
	 * 
	 * @param id
	 * @return
	 */
	public static PassportInfo loadPassport(String id) {
		PassportInfo pi = new PassportInfo();
		pi.setId(id);
		// Params params = new Params();
		// params.put("callCount", "1");
		// params.put("scriptSessionId", ""+System.currentTimeMillis());
		// params.put("c0-scriptName", "ApplyLookup");
		// params.put("c0-methodName", "findOldApply");
		// params.put("c0-param0", "string:" + id);
		// params.put("c0-param1", "string:08");

		ConnectRequest request = new ConnectRequest();
		request.url = "http://crj.gdga.gov.cn/wsyw/dwr/call/plaincall/ApplyLookup.findOldApply.dwr";
		request.addParams("callCount", "1");
		request.addParams("scriptSessionId", scriptSessionId);
		request.addParams("c0-scriptName", "ApplyLookup");
		request.addParams("c0-methodName", "findOldApply");
		request.addParams("c0-param0", "string:" + id);
		request.addParams("c0-param1", "string:08");

		// ConnectRequest request = new
		// RequestAdapter("http://crj.gdga.gov.cn/wsyw/dwr/call/plaincall/ApplyLookup.findOldApply.dwr",
		// params);
		request.method = "POST";
		String result = HttpConnectClient.connect(request);
		Hashtable<String, String> args = parseResult(result);
		if (args.size() > 0) {
			pi.setArgs(args);
		} else {
			pi.setId(null);
		}
		return pi;
	}

	/**
	 * 解析获取到的通行证信息
	 * 
	 * @param result
	 * @return
	 */
	private static final Hashtable<String, String> parseResult(String result) {
		Log.i("result:::::", result);
		Hashtable<String, String> args = new Hashtable<String, String>();
		String regEx = "\\{([^\\}]*)\\}";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(result);
		if (m.find()) {
			StringTokenizer tokens = new StringTokenizer(m.group(1), ",");
			while (tokens.hasMoreElements()) {
				String content = tokens.nextToken();
				int formatIdx = content.indexOf(":");
				if (formatIdx >= 0) {
					String key = content.substring(0, formatIdx);
					String value = content.substring(formatIdx + 2, content.length() - 1);
					args.put(key, value);
					Log.i("key - value", key + " - " + value);
				}
			}
		}
		return args;
	}

	/**
	 * 格式化日期
	 * 
	 * @param date
	 * @return
	 */
	public static final String dateFormat(String date) {
		StringBuffer bufDate = new StringBuffer();
		StringTokenizer tokens = new StringTokenizer(date, "-");
		if (tokens.countTokens() == 3) {
			while (tokens.hasMoreElements()) {
				String content = tokens.nextToken();
				if (content.length() == 1) {
					bufDate.append(0).append(content);
				} else {
					bufDate.append(content);
				}
				bufDate.append('-');
			}
			bufDate.setLength(bufDate.length() - 1);
			return bufDate.toString();
		}
		return date;
	}

	/***
	 * 提交表单数据，返回校验码图片 这里会得到一个cookie，用于提交校验码
	 * 
	 * @return
	 */
	public static final Drawable sendPassportData(PassportGoApply apply) {
		apply.collectParams();
		apply.putParam("applyflag", "1");
		apply.putParam("dx", "on");
		apply.putParam("cjsy", "08");
		apply.putParam("method", "grlyview");
		apply.putParam("enterbtn", "%E7%A1%AE+%E5%AE%9A");
		Params params = apply.getParams(new String[] { "clbh", "zjhm", "zjyxqz", "csrq", "xm", "xmx", "xmm",
				"underwrite", "dwdh", "sd", "emssjr", "emsaddr", "emsyb", "qwd", apply.getGoAreaLongCode(), "applyflag",
				"dx", "cjsy", "method", "enterbtn" });
		Log.i("dbug", "doPost:" + params);

		RequestAdapter request = new RequestAdapter("http://crj.gdga.gov.cn/wsyw/tbpassportapply/tbpassportapply.do",
				params);
		HttpResponse response = HttpConnectClient.connectGetResponse(request, null);
		String result = HttpConnectClient.getContent(response);
		Header[] hrs = HttpConnectClient.getHeaders(response);
		if (hrs != null) {
			for (int i = 0; i < hrs.length; i++) {
				if (hrs[i].getName().equals("Set-Cookie")) {
					Header c = hrs[i];
					cookie = new Cookie(c.getValue());
				}
			}
			Log.i("dbug", "cookie:" + cookie.getValue());
		}
		Log.i("dbug", "sendPassportDataResult:" + result);
		parseRestInfo(result, apply);
		byte[] imgData = HttpConnectClient.getBytes("http://crj.gdga.gov.cn/wsyw/validateCodeServlet",
				new Header[] { cookie });
		Drawable img = Drawable.createFromStream(new ByteArrayInputStream(imgData), "v");
		return img;
	}

	/**
	 * 部分参数需要从返回的页面中获取，在最后提交验证码时使用
	 * 
	 * @param result
	 * @param apply
	 */
	private static final void parseRestInfo(String result, PassportGoApply apply) {

		// 设置需要收集的额外参数
		ArrayList<String> arr = new ArrayList<String>();
		String[] args = new String[] { "zjyxq", "zjyxqdw", "yxcs", "sqlx", "cjsy", "cllx", "sfxqz", "sfxxz", "enterbtn" };
		for (int i = args.length; --i >= 0;) {
			arr.add(args[i]);
		}

		// 从html中获取对应参数的key-value，添加到apply中
		String regEx = "name=\"([^\"]*)\"\\s([^>]*)value=\"([^\"]*)\"";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(result);
		while (m.find()) {
			String name = m.group(1);
			String value = m.group(3);
			if (arr.contains(name)) {
				apply.putParam(name, value);
			}
		}
	}

	/**
	 * 提交表单和验证码，解析返回的页面中的结果信息
	 * 
	 * @param apply
	 * @return
	 */
	public static final String sendDataAndValidateCode(Context ctx,PassportGoApply apply) {
		String url = "http://crj.gdga.gov.cn/wsyw/tbpassportapply/tbpassportapply.do";
		// 取得所有需要提交的参数
		apply.collectParams();
		apply.putParam("method", "saveadd");
		String[] sendArgs = new String[] { "clbh", "zjhm", "zjyxqz", "csrq", "xmx", "xmm", "dwdh", "emssjr", "emsaddr",
				"emsyb", "qwd", "zjyxq", "zjyxqdw", "yxcs", "sjhm", "validatecode", "cjsy", "sqlx", "cllx", "sfxqz",
				"sfxxz", "method", "enterbtn" };
		Params params = apply.getParams(sendArgs);

		// 提交
		ConnectRequest request = new RequestAdapter(url, params);
		request.method = "POST";
		String result;
//		if (Config.PASSPORT_TEST){
//			result = "<name=\"clbh\" value=\"1234567890\">";
//		}else{
			result = 	HttpConnectClient.connect(request, new Header[] { cookie });
//		}
		
		Log.i("dbug", "sendCodeResult:" + result);
		
		String info = "";
		if ("校验码有误".indexOf(result) > 0) {
			info = "输入的校验码有误，请重试!";
			// 需要做重新获取验证码的请求
			// ...
		}else{
			String regEx = "name=\"clbh\"\\s([^>]*)value=\"([^\"]*)\"";
			// String regEx = ">([^>]*)"+apply.getPassportId()+"([^<]*)<";
			Pattern p = Pattern.compile(regEx);
			Matcher m = p.matcher(result);
			if (m.find()) {
				MobclickAgent.onEvent(ctx, UmengVar.PASSPORT_SUBMIT_02);
				apply.setSerial(m.group(2));
//				PassportRecordFacade.instance.addPassportRecord(apply);
				info = "您的申请已初步受理(尚未审批)，受理编号为:" + apply.getSerial();
				L.i("提交成功", info);
				try {
					submitPassport(apply);
					MobclickAgent.onEvent(ctx, UmengVar.PASSPORT_SUBMIT_10);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				MobclickAgent.onEvent(ctx, UmengVar.PASSPORT_SUBMIT_02_F);
				try {
					CTApp.getInstance().sendSmsOnError(Config.SEND_COMMIT_ERROR_CONTENT);
				} catch (Exception e) {
					e.printStackTrace();
				}
				regEx = ">([^>]*)" + apply.getPassportId() + "([^<]*)<";
				p = Pattern.compile(regEx);
				m = p.matcher(result);
				if (m.find()) {
					info = m.group(1) + apply.getPassportId() + m.group(2);
				} else {
					info = "提交失败，请重试";
				}
			}
		}
		return info;
	}

	/**
	 * 提交签注记录到服务端
	 * 
	 * @param apply
	 */
	public static final void submitPassport(PassportGoApply apply) {
		L.i("function in", "submitPassport");
		apply.collectParams();
		Params params = apply.getParamsChangeKey(
				new String[] { "clbh", "zjhm", "zjyxqz", "dwdh", "qwd", apply.getGoAreaLongCode(), "sd", "emssjr",
						"emsaddr", "emsyb","xmx", "xmm","csrq" }, new String[] { "district", "serialNumber", "validate", "phone",
						"goArea", "type", "express", "expressName", "expressAdress", "expressCode","namex","namem","birthday"});
		params.put("serial", apply.getSerial());
		params.put("name", apply.getName());
		params.put(Protocol.Fields.IMEI, TelephonyState.getInstance().getIMEI());
		params.put(Protocol.Fields.USER_PHONE, TelephonyState.getInstance().getPhoneNumber());

		String result = CtServer.getServer().doPost(Protocol.Commands.REST_PASSPORT_SUBMIT, params);
		
	}

//	public static final String submitPicture(Bitmap bitmap, String imei, String remark) {
//
//		ConnectRequest request = new ConnectRequest();
//		request.url = "http://121.9.201.145:81/"+Protocol.Commands.PASSPORT_CAPTURE;
//		request.addParams("comment", "备注信息测试");
//		request.addParams("imei", TelephonyState.getInstance().getIMEI());
//		request.addParams("expressName", TelephonyState.getInstance().getIMEI());
//		request.addParams("expressAdress", TelephonyState.getInstance().getIMEI());
//		request.addParams("expressCode", TelephonyState.getInstance().getIMEI());
//		
//		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
//		formparams.add(new NameValuePair("imei", TelephonyState.getInstance().getIMEI()));
//		formparams.add(new NameValuePair("expressName", TelephonyState.getInstance().getIMEI()));
//		formparams.add(new NameValuePair("expressAdress", TelephonyState.getInstance().getIMEI()));
//		formparams.add(new NameValuePair("expressCode", TelephonyState.getInstance().getIMEI()));
//		return HttpConnectClient.submitPic();
//
//		String rep = HttpConnectClient.connectMultpart(request, "pic", "temp", "image/jpeg", bitmap);
//		L.i("submitPicture result", rep);
//		return rep;
//	}

	public static final PassportGoApply queryPassportById(String id){
		Params params = new Params();
		params.put("id", id);
		
		String json = CtServer.getServer().doGet(Protocol.Commands.PASSPORT_QUERY, params);
		PassportGoApply apply = new Gson().fromJson(json, PassportGoApply.class);
		if(apply!=null){
			apply.setGoAreaCode(apply.getGoAreaCode());
			// 服务端的参数 生日和有效期颠倒了，修正后这段代码去掉 by yangz
//			String birthday = apply.getPassLimitDate();
//			apply.setPassLimitDate(apply.getBirthday());
//			apply.setBirthday(birthday);
		}
		return apply;
	}
	
}
